<template>
  <div class="add-quality-report">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>质检工序报工</span>
          <el-tag :type="formData.status === '已完成' ? 'success' : 'warning'" class="status-tag">
            {{ formData.status || '待质检' }}
          </el-tag>
        </div>
      </template>
      
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
        class="quality-form"
      >
        <!-- 基本信息部分 -->
        <div class="form-section">
          <h3>基本信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="工序编码" prop="processCode">
                <el-input v-model="formData.processCode" placeholder="请输入工序编码" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工序名称" prop="processName">
                <el-input v-model="formData.processName" placeholder="请输入工序名称" disabled />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="加工顺序" prop="processingOrder">
                <el-input v-model="formData.processingOrder" placeholder="请输入加工顺序" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工艺流程" prop="processFlow">
                <el-input v-model="formData.processFlow" placeholder="请输入工艺流程" disabled />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 质检信息部分 -->
        <div class="form-section">
          <h3>质检信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="质检负责人" prop="person">
                <el-select 
                  v-model="formData.person" 
                  placeholder="请选择质检负责人"
                  style="width: 100%"
                >
                  <el-option label="王浩然" value="王浩然"/>
                  <el-option label="张三" value="张三"/>
                  <el-option label="李四" value="李四"/>
                  <el-option label="李雪妮" value="李雪妮"/>
                  <el-option label="赵世豪" value="赵世豪"/>
                  <el-option label="张豪" value="张豪"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="质检部门" prop="department">
                <el-select 
                  v-model="formData.department" 
                  placeholder="请选择质检部门"
                  style="width: 100%"
                >
                  <el-option label="包装部" value="包装部"/>
                  <el-option label="生产部" value="生产部"/>
                  <el-option label="酵母部" value="酵母部"/>
                  <el-option label="原料部" value="原料部"/>
                  <el-option label="发酵部" value="发酵部"/>
                  <el-option label="采购部" value="采购部"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="报工时间" prop="reportingTime">
                <el-date-picker
                  v-model="formData.reportingTime"
                  type="datetime"
                  placeholder="请选择报工时间"
                  style="width: 100%"
                  :disabled-date="disableFutureDate"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="完工数量" prop="quantity">
                <el-input-number 
                  v-model="formData.quantity" 
                  :min="0"
                  style="width: 100%"
                  placeholder="请输入完工数量"
                  disabled
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 质检结果部分 -->
        <div class="form-section">
          <h3>质检结果</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="合格数量" prop="qualifiedQuantity">
                <el-input-number 
                  v-model="formData.qualifiedQuantity" 
                  :min="0"
                  :max="formData.quantity"
                  style="width: 100%"
                  placeholder="请输入合格数量"
                  @change="calculateUnqualifiedQuantity"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="不合格数量" prop="unqualifiedQuantity">
                <el-input-number 
                  v-model="formData.unqualifiedQuantity" 
                  :min="0"
                  style="width: 100%"
                  disabled
                  placeholder="不合格数量"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="不合格原因" prop="unqualifiedReason">
                <el-input
                  v-model="formData.unqualifiedReason"
                  type="textarea"
                  :rows="3"
                  placeholder="请详细描述不合格原因"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <el-form-item>
          <el-button type="primary" @click="submitQualityReport">提交质检结果</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
  import { ref, reactive, onMounted, watch } from 'vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { useRouter, useRoute } from 'vue-router';
  import { Materialread, Materialwrite } from '@/axios/axiosHelper';
  import axios from 'axios';
  import { th } from 'element-plus/es/locales.mjs';
  
  const formRef = ref(null);
  const currentUser = ref("admin");
  const router = useRouter();
  const route = useRoute();
  
  // 主表单数据
  const formData = reactive({
        qualityReportWorkid:  route.params.qualityReportWorkid,
        processCode: '',
        processName: '',
        processingOrder: '',
        processFlow: '',
        person: '',
        department: '',
        reportingTime: '',
        quantity: 0,
        productionPersonnel: '',
        departmentSS: '',
        reportingpersonnel: currentUser.value,
        qualifiedQuantity: 0,
        unqualifiedQuantity: 0,
        unqualifiedReason: null,
        status: '',
        isDel: true
  });

  // 禁用未来日期
  const disableFutureDate = (time) => {
    return time.getTime() > Date.now();
  };

  // 计算不合格数量
  const calculateUnqualifiedQuantity = () => {
    formData.unqualifiedQuantity = Math.max(0, formData.quantity - formData.qualifiedQuantity);
  };

  // 修改表单验证规则
  const rules = reactive({
    person: [
      { required: true, message: '请选择质检负责人', trigger: 'change' }
    ],
    department: [
      { required: true, message: '请选择质检部门', trigger: 'change' }
    ],
    reportingTime: [
      { required: true, message: '请选择报工时间', trigger: 'change' }
    ],
    qualifiedQuantity: [
      { required: true, message: '请输入合格数量', trigger: 'blur' },
      { type: 'number', min: 0, message: '合格数量不能小于0', trigger: 'blur' },
      { 
        validator: (rule, value, callback) => {
          if (value > formData.quantity) {
            callback(new Error('合格数量不能超过完工数量'));
          } else {
            callback();
          }
        }, 
        trigger: 'blur' 
      }
    ],
    unqualifiedReason: [
      { 
        validator: (rule, value, callback) => {
          if (formData.unqualifiedQuantity > 0 && !value) {
            callback(new Error('请填写不合格原因'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ]
  });

  const getProductionById = (qualityReportWorkid) => {
    console.log('查看反填数据:', qualityReportWorkid);
    Materialread.get('f-read/api/Arrival/FTQualityReportWork', {
        params:{
            qualityReportWorkid: route.query.qualityReportWorkid
        }
      })
      .then(res=>{
        if (res.data.code === 200 && res.data.data && res.data.data.length > 0) {
          const data = res.data.data[0];
          Object.assign(formData, {
            qualityReportWorkid: data.qualityReportWorkid,
            processCode: data.processCode,
            processName: data.processName,
            processingOrder: data.processingOrder,
            processFlow: data.processFlow,
            person: data.person,
            department: data.department,
            reportingTime: data.reportingTime,
            quantity: data.quantity || 0,
            productionPersonnel: data.productionPersonnel,
            departmentSS: data.departmentSS,
            reportingpersonnel: data.reportingpersonnel,
            qualifiedQuantity: data.qualifiedQuantity || 0
          });
          // 计算初始不合格数量
          calculateUnqualifiedQuantity();
          console.log('反填数据:', formData);
        }
      })
      .catch(error => {
        console.error('获取数据出错:', error);
        ElMessage.error('获取数据失败');
      });
  };

  // 提交质检结果
  const submitQualityReport = () => {
    formRef.value.validate((valid) => {
      if (valid) {
        // 更新状态为已完工
        formData.status = '已完工';
        
        // 添加确认对话框
        ElMessageBox.confirm(
          '确认提交质检结果？提交后将更新工单状态为已完工。',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          Materialwrite.post('f-write/api/Arrival/UpdateQualityReportWork', formData)
            .then(response => {
              if (response.data.code === 200) {
                ElMessage.success('质检结果提交成功，状态已更新为已完工');
                router.push("/GetQualityReportWork");
              } else {
                ElMessage.error(`提交失败：${response.data.message}`);
              }
            })
            .catch(error => {
              console.error('保存出错:', error);
              ElMessage.error('保存时出现错误，请检查网络或重试');
            });
        }).catch(() => {
          ElMessage.info('已取消提交');
        });
      } else {
        ElMessage.error('请填写完整且正确的质检信息');
        return false;
      }
    });
  };

  // 重置表单
  const resetForm = () => {
    ElMessageBox.confirm(
      '确认重置表单？所有已填写的信息将被清空。',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      formRef.value.resetFields();
      calculateUnqualifiedQuantity();
      ElMessage.success('表单已重置');
    }).catch(() => {
      ElMessage.info('已取消重置');
    });
  };

  onMounted(()=>{
    getProductionById();
  })
</script>
    
<style scoped>
.add-quality-report {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.status-tag {
  margin-left: 10px;
}

.form-section {
  margin-bottom: 30px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.form-section h3 {
  margin: 0 0 20px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #e9ecef;
  color: #2c3e50;
  font-size: 18px;
}

.quality-form {
  max-width: 1200px;
  margin: 0 auto;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-input,
.el-select,
.el-date-picker,
.el-input-number {
  width: 100%;
}

.el-textarea__inner {
  min-height: 100px;
}

.el-button {
  margin-right: 15px;
  padding: 12px 24px;
}

.el-button--primary {
  background-color: #409EFF;
  border-color: #409EFF;
}

.el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}
</style>